package logic

import (
	"context"
	"database/sql"
	"errors"
	"game/model"

	"game/rpc/gamerpc/game"
	"game/rpc/gamerpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateUserLogic {
	return &CreateUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateUserLogic) CreateUser(in *game.CreateUserRequest) (*game.CreateUserResponse, error) {
	// 校验用户名是否已存在
	_, err := l.svcCtx.UsersModel.FindOneByUsername(l.ctx, in.User.Username)
	if err == nil {
		return nil, errors.New("用户名已存在")
	} else if !errors.Is(err, model.ErrNotFound) {
		return nil, err
	}

	// 校验邮箱是否已存在
	if in.User.Email != "" {
		_, err := l.svcCtx.UsersModel.FindOneByEmail(l.ctx, sql.NullString{String: in.User.Email, Valid: true})
		if err == nil {
			return nil, errors.New("邮箱已存在")
		} else if !errors.Is(err, model.ErrNotFound) {
			return nil, err
		}
	}

	// 构造用户数据
	user := &model.Users{
		Username: in.User.Username,
		Password: in.User.Password, // 明文存储密码（不推荐）
		Email:    sql.NullString{String: in.User.Email, Valid: in.User.Email != ""},
	}

	// 插入用户数据
	result, err := l.svcCtx.UsersModel.Insert(l.ctx, user)
	if err != nil {
		return nil, err
	}

	// 获取插入的用户ID
	userId, _ := result.LastInsertId()
	return &game.CreateUserResponse{Id: int32(userId)}, nil

}
